<script setup>
import {useSidebarStore} from "@/stores/sidebar.js";
import {useMenuStore} from "@/stores/menu.js";
import {computed} from 'vue';
import {useRoute} from 'vue-router';
import {useUserStore} from '@/stores/pages/user.js';
import router from "@/router/index.js";

import {IndentLeft, IndentRight, User} from "@icon-park/vue-next";

const sidebarStore = useSidebarStore();
const menuStore = useMenuStore();
const userStore = useUserStore();
const route = useRoute();

const handleToggle = () => {
  sidebarStore.toggle();
}

// 检查菜单项是否应该可点击
// 如果菜单项有对应的路由或有children，则可点击
const isMenuItemClickable = (item) => {
  // 检查是否有对应的路由组件（简单检查index是否匹配一个实际路由）
  const hasRoute = item.index && !item.index.startsWith('#');

  // 如果有children，通常表示它是一个分组，不一定有页面
  const hasChildren = item.children && item.children.length > 0;

  // 如果有明确的路由路径，则可点击
  return hasRoute && !hasChildren;
}

// 计算面包屑路径
const breadcrumbItems = computed(() => {
  // 确保menuList存在
  const menuList = menuStore.menuList || [];
  const path = route.path;

  // 查找匹配的菜单项
  const findMenuItems = (menuList, path) => {
    // 保护性检查
    if (!menuList || !Array.isArray(menuList)) {
      return null;
    }

    for (const item of menuList) {
      // 直接匹配
      if (item && item.index === path) {
        return [item];
      }

      // 查找子菜单
      if (item && item.children && item.children.length > 0) {
        const childMatch = findMenuItems(item.children, path);
        if (childMatch) {
          return [item, ...childMatch];
        }
      }
    }

    return null;
  };

  // 特殊处理根路径
  if (path === '/' || path === '/app/dashboard') {
    const dashboardItem = menuList.find && menuList.find(item => item && item.index === '/app/dashboard');
    if (dashboardItem) {
      return [dashboardItem];
    }
    return [{title: '仪表盘', index: '/app/dashboard'}];
  }

  // 查找匹配的菜单项
  const matchedItems = findMenuItems(menuList, path);
  if (matchedItems) {
    return matchedItems;
  }

  // 如果没有找到匹配项，返回默认项
  return [{title: '页面未找到', index: path}];
});

// 为面包屑项计算是否可点击
const breadcrumbItemsWithClickable = computed(() => {
  return breadcrumbItems.value.map(item => {
    return {
      ...item,
      clickable: isMenuItemClickable(item)
    };
  });
});

// 获取当前用户角色
const userRoles = computed(() => {
  return userStore.getUserRoles()
})

// 获取显示的角色名称和类名
const displayRole = computed(() => {
  const roles = userRoles.value
  if (roles.includes('SUPER_ADMIN')) {
    return { name: '超级管理员', class: 'super-admin' }
  } else if (roles.includes('ADMIN')) {
    return { name: '管理员', class: 'admin' }
  } else {
    return { name: '普通用户', class: 'user' }
  }
})

// 获取用户名
const userName = computed(() => {
  return userStore.user?.name || '未知用户'
})

// 处理用户名显示（长文本截断）
const displayName = computed(() => {
  const name = userName.value
  return name.length > 6 ? name.substring(0, 6) + '...' : name
})

// 个人设置跳转
const goToPersonalSettings = () => {
  router.push({ name: 'PersonalSettings' });
}

</script>

<template>
  <div class="app-header">
    <button @click="handleToggle" :aria-label="sidebarStore.isCollapse ? '展开侧边栏' : '收起侧边栏'">
      <IndentRight v-if="sidebarStore.isCollapse" :size="24" theme="outline" class="indent-btn"/>
      <IndentLeft v-else :size="24" theme="outline" class="indent-btn"/>
    </button>

    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/" class="breadcrumb">
      <el-breadcrumb-item
          v-for="(item, index) in breadcrumbItemsWithClickable"
          :key="item.index || index"
          :to="item.clickable && index !== breadcrumbItemsWithClickable.length - 1 ? item.index : ''"
      >
        {{ item.title }}
      </el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 功能区   -->
    <div class="app-header-function-area">
      <!-- 头像  -->
      <el-dropdown>
        <div class="user-info" :class="displayRole.class">
          <User :size="35" theme="outline" class="user-avatar"/>
          <div class="user-text">
            <span class="user-name">{{ displayName }}</span>
            <span class="user-role" :class="displayRole.class">{{ displayRole.name }}</span>
          </div>
        </div>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="goToPersonalSettings">个人设置</el-dropdown-item>
            <el-dropdown-item >修改密码</el-dropdown-item>
            <el-dropdown-item @click="userStore.logout()">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>

    </div>
  </div>
</template>

<style scoped>
.app-header {
  width: 100%;
  display: flex;
  align-items: center;
  padding: 0 20px;
}

button {
  border: none;
  background: none;
  cursor: pointer;
  margin: 6px 20px 0 0;
}

.indent-btn{
  color: var(--indent-btn-color);
}

.breadcrumb {
  flex: 1;
  white-space: nowrap; /* 防止换行 */
  -webkit-user-select: none; /* Safari */
  -moz-user-select: none; /* Firefox */
  -ms-user-select: none; /* IE10+ */
  user-select: none;
}

/* 面包屑样式定制 */
:deep(.el-breadcrumb__inner) {
  font-size: 17px; /* 设置字体大小 */
  font-weight: bold;
}

:deep(.el-breadcrumb__item:last-child .el-breadcrumb__inner) {
  color: var(--breadcrumb-text); /* 设置当前页面的颜色 */
  font-weight: bold;
  cursor: default;
}

.app-header-function-area {
  width: auto;
  padding: 2px;
  display: flex;
  justify-content: flex-end;
  margin-right: -10px;
}

.user-info {
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  border-radius: 5px;
  padding: 5px;

  .user-avatar {
    border: 2px solid var(--user-avatar-border-color);
    border-radius: 50%;
    overflow: hidden;
    width: auto;
    color: var(--user-avatar-color);
  }

  .user-text {
    display: flex;
    flex-direction: column;
    line-height: 1.3;
    margin-left: 10px;
    width: 110px;

    .user-name {
      font-size: 14px;
      font-weight: 600;
      color:var(--user-name-color);
    }

    .user-role {
      font-size: 12px;
      color: #666;
    }
  }
}

/* 根据用户角色渲染对应字体颜色 */
.user-role.super-admin {
  background: linear-gradient(45deg, red, #e49ead, #eca7bd);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  font-weight: bold;
}

:deep(.user-role.admin) {
  color: #409eff !important;
  font-weight: bold;
}

:deep(.user-role.user) {
  color: #67c23a !important;
  font-weight: bold;
}

/* 根据用户角色渲染对应阴影 */
.user-info.super-admin{
  box-shadow: 0 -10px 15px -17px #f34848,
  0 10px 15px -17px #f34848;
}

.user-info.admin{
  box-shadow: 0 -10px 15px -17px #409eff,
  0 10px 15px -17px #409eff;
}

.user-info.user{
  box-shadow: 0 -10px 15px -17px #67c23a,
  0 10px 15px -17px #67c23a;
}
</style>

<style>
.el-dropdown-menu{
  background: #ffffff;
  padding: 0;
}

.el-dropdown-menu__item:hover{
  background: black !important;
  color: #ffffff !important;
}

/* 取消下拉框的黑框 */
.el-tooltip__trigger:focus-visible {
  outline: unset;
}

/* 隐藏三角形 */
.el-popper__arrow {
  display: none;
}
</style>